/*
 * Licensed Materials - Property of tenxcloud.com
 * (C) Copyright 2018 TenxCloud. All Rights Reserved.
 * 2018-06-13  @author lizhen
 */

package utility

import (
	_ "github.com/go-sql-driver/mysql"
	_ "github.com/jinzhu/gorm/dialects/mysql"

	"github.com/jinzhu/gorm"
)

type config interface {
	MySQLDSN() string
	RunMode() string
}

func NewDatabase(config config) *db {
	return &db{
		db: NewLazy(func() (value interface{}, err error) {
			var d *gorm.DB
			if d, err = gorm.Open("mysql", config.MySQLDSN()); err != nil {
				return
			}
			d.LogMode(config.RunMode() == "debug")
			value = d
			return
		}),
	}
}

type db struct {
	db Lazy
}

func (s db) GetOrm() (db *gorm.DB, err error) {
	if err = s.db.Value(&db); err != nil {
		return
	}
	return
}
